const path = require('path')
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const koaStatic = require('koa-static')

const session = require('koa-generic-session')
const redisStore = require('koa-redis')
const REDIS_CONFIG = require('./config/db')
const {
  SESSION_SECRET_KEY
} = require('./config/secretKeys')

const users = require('./routes/users')
const homeApiRouter = require('./routes/api/blog-home')
const blogViewRouter = require('./routes/view/blog')
const userViewRouter = require('./routes/view/user')
const userApiRouter = require('./routes/api/user')
const utilsApiRouter = require('./routes/api/utils')
const profileApiRouter = require('./routes/api/blog-profile')
const squareApiRouter = require('./routes/api/blog-square')
const blogAtApiRouter = require('./routes/api/blog-at')
const errorViewRouter = require('./routes/view/error')

const {
  isProd
} = require('./utils/env')

// error handler
let onErrorConfig = {}
if (isProd) {
  onErrorConfig = {
    redirect: '/error'
  }
}
onerror(app, onErrorConfig)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(koaStatic(__dirname + '/public'))
app.use(koaStatic(path.join(__dirname, '..', 'uploadFiles')))

app.use(views(__dirname + '/views', {
  extension: 'ejs'
}))

// session配置
app.keys = [SESSION_SECRET_KEY]
app.use(session({
  key: 'twitter.sid', // cookie name 默认koa.sid
  prefix: 'twitter:sess:', // redis key 前缀 默认koa:sess
  cookie: {
    path: '/',
    httpOnly: true, //禁止客户端修改cookie
    maxAge: 20 * 60 * 60 * 1000 // ms
  },
  store: redisStore({
    all: `${REDIS_CONFIG.host}:${REDIS_CONFIG.port}`
  })
}))

// routes
app.use(users.routes(), users.allowedMethods())
app.use(homeApiRouter.routes(), homeApiRouter.allowedMethods())
app.use(blogViewRouter.routes(), blogViewRouter.allowedMethods())
app.use(userViewRouter.routes(), userViewRouter.allowedMethods())
app.use(userApiRouter.routes(), userApiRouter.allowedMethods())
app.use(utilsApiRouter.routes(), utilsApiRouter.allowedMethods())
app.use(profileApiRouter.routes(), profileApiRouter.allowedMethods())
app.use(squareApiRouter.routes(), squareApiRouter.allowedMethods())
app.use(blogAtApiRouter.routes(), blogAtApiRouter.allowedMethods())
app.use(errorViewRouter.routes(), errorViewRouter.allowedMethods()) // 404

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app